/*
* Author: Foldcc
* Mail:   lhyuau@qq.com
*/

using System;
using System.Collections.Generic;
using ToffeeHttp.Runtime;
using ToffeeHttp.Runtime.Core;
using UnityEngine;

namespace Test.Simple2
{
    public class Sample : MonoBehaviour
    {
        public string Url;
        public int Port;
        public string Method;
        public string DataKey;
        public string DataValue;
        
        public ToffeeHttpClient Client;

        private void Awake()
        {
            this.Client = new ToffeeHttpClient();
            //使用默认Handler以及MsgChannel发送数据， 可自行扩展Handler与MsgChannel
            this.Client.AppendServer<GetHandlerFrom, MsgChannelDefault>(this.Url, this.Port, 20, "Test_Get");
            this.Client.AppendServer<PostHandlerForm, MsgChannelDefault>(this.Url, this.Port, 20, "Test_Post");
        }

        public void HttpSend_GET()
        {
            //使用wwwfrom方式
            WWWForm wwwForm = new WWWForm();
            wwwForm.AddField(this.DataKey , this.DataValue);
            //使用Dictionary方式
            Dictionary<string, object> data = new Dictionary<string, object>();
            data[this.DataKey] = this.DataValue;
            //发送
            this.Client.HttpSend("Test_Get" , this.Method , wwwForm , this.OnHttpResponse );
            // this.Client.HttpSend(this.Method , data , this.OnHttpResponse , "Test_Get");
        }
        
        public void HttpSend_Post()
        {
            WWWForm wwwForm = new WWWForm();
            wwwForm.AddField(this.DataKey , this.DataValue);
            this.Client.HttpSend("Test_Post" , this.Method , wwwForm , this.OnHttpResponse );
        }

        /// <summary>
        /// 快捷发送，一般用于测试阶段， 不需要提前将服务器信息注册到Client配置表中【this.Client.AppendServer】
        /// </summary>
        public void HttpQuickSend_Get()
        {
            var uri = this.Url + ":" +this.Port +  this.Method + $"?{this.DataKey}={this.DataValue}";
            this.Client.QuickHttpSend(uri, null , this.OnHttpResponse);
        }
        /// <summary>
        /// 快捷发送，可以做到与正常发送相同操作，可自定义MsgChannel和Handler , 如果不指定则默认使用 GetHandlerString 方式请求
        /// </summary>
        public void HttpQuickSend_Post()
        {
            this.Client.QuickHttpSend(this.Url + ":" +this.Port + this.Method , null , this.OnHttpResponse , new PostHandlerForm() , new MsgChannelDefault());
        }
        
        private void OnHttpResponse(HttpResponse obj)
        {
            if (obj.IsError)
            {
                Debug.LogError(obj.WebRequest.error);
            }
            else
            {
                Debug.Log("收到请求： " + obj.Content);
            }
        }
    }
}